package com.h3bpm.kumhosunny.crm.controller;

import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.Notification.DingTalk.*;
import OThinker.H3.Entity.Notification.Notification;
import OThinker.H3.Entity.Notification.NotifyType;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import data.DataRow;
import data.DataTable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.crypto.Data;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @authormi
 * @date2019/10/30
 */
@Controller
@RequestMapping({"/Portal/UnitGetCrm"})
public class GetUnitController extends ControllerBase {


    @Override
    public String getFunctionCode() {
        return null;
    }



    public String getAppPerson(String userId){


        Unit user = null;
        String appCode="";
        try {
            user = (User) getEngine().getOrganization().GetUnit(userId);
             if(user!=null) {
                 appCode = ((User) user).getCode();
                 if (user.getManagerID() != null) {
                     appCode = getParentPeson(user.getObjectID(), appCode);
                 } else {
                     appCode = getParentPeson(user.getObjectID(), appCode);
                 }
             }
        } catch (Exception e) {
            e.printStackTrace();
        }
       return appCode;

    }



    public String getParentPeson(String unitId,String appCode) throws Exception {
        User unit = (User)   getEngine().getOrganization().GetUnit(unitId);
        Unit unitOrg =    getEngine().getOrganization().GetUnit(unit.getParentID());
        if(unit.getManagerID()!=null && !"".equals(unit.getManagerID()) && !unit.getManagerID().equals(unit.getObjectID())){
            User unitParent =   (User) getEngine().getOrganization().GetUnit(unit.getManagerID());
            appCode  = appCode+";"+unitParent.getCode();
            appCode= getParentPeson( unitParent.getObjectID(),  appCode);

        }else if(unitOrg.getManagerID()!=null && !"".equals(unitOrg.getManagerID()) && !unit.getObjectID().equals(unitOrg.getManagerID())){
            User user = (User)   getEngine().getOrganization().GetUnit(unitOrg.getManagerID());
            appCode=appCode+";"+user.getCode() ;
            appCode=getParentPeson( user.getObjectID(),  appCode);
        }else{
            appCode=appCode+";"+unit.getCode();
            return appCode;

        }
        return appCode;
    }


    @RequestMapping("/UnitGet")
    @ResponseBody
    public JSONObject getBoList(String userId)   {

        JSONObject result= new JSONObject();
        try {
          String appCode =   getAppPerson(userId);
            User user = (User)   getEngine().getOrganization().GetUnit(userId);
            if(user!=null && user.getParentID()!=null){
                Unit unit = getEngine().getOrganization().GetUnit( user.getParentID());
               List<String> userIds= getEngine().getOrganization().GetUsersByJobCode(unit.getObjectID(),"nqPerson",null);
             if(userIds!=null && userIds.size()>0){
                 for(String uid  : userIds){
                     User userNq = (User)   getEngine().getOrganization().GetUnit(uid);
                     appCode=appCode+";"+userNq.getCode();
                 }
             }

            }

        result.put("status","200");
        result.put("data",appCode);
        return result;
        } catch (Exception e) {
            result.put("status","500");
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping("/testSendMessage")
    @ResponseBody
    public JSONObject testSendMessage(   )   {

        JSONObject result= new JSONObject();
        result.put("status",200);
        try {

            Notification notification = new Notification(NotifyType.DingTalk,null,null,"18336380660",null,-1,"17c952c4-4c0c-4e54-be5b-29ee978fbd8a","test","<a href='www.baidu.com'>test</a>",null,"http://www.baidu.com",null);
            getEngine().getNotifier().Notify(notification);

        } catch (Exception e) {
            result.put("status","500");
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping("/updateApproveList")
    @ResponseBody
    public JSONObject synchronizationCrm(String oldPersonCode ,String newPersonCode ) {
        JSONObject result= new JSONObject();
        try {
        if(oldPersonCode!=null && !"".equals(oldPersonCode) && newPersonCode!=null  &&!"".equals(newPersonCode) ) {

             User newUser =   getEngine().getOrganization().GetUserByCode(newPersonCode);
             User oldUser =   getEngine().getOrganization().GetUserByCode(oldPersonCode);
             if(newUser!=null && oldUser!=null) {
                 String updateCustomerProfileSql = "update i_CustomerProfile   set   salesman  ='" + newUser.getObjectID() + "' where  salesman='" + oldUser.getObjectID()+"'";

                 String updateContactFileManagerSql = "update i_ContactFileManager   set   exclusiveSalesman  ='" + newUser.getObjectID() + "' where  exclusiveSalesman='" + oldUser.getObjectID()+"'";

                 String updateSampleApplicationSql = "update i_sampleApplication   set   applicant  ='" + newUser.getObjectID() + "' where  applicant='" + oldUser.getObjectID()+"'";

                 SqlUtil.doNoQuery(updateCustomerProfileSql);
                 SqlUtil.doNoQuery(updateContactFileManagerSql);
                 SqlUtil.doNoQuery(updateSampleApplicationSql);
             }
            }
                updateUserAppList(  "CustomerProfile" ,  "appDatas" ,  "salesman");
                updateUserAppList(  "ContactFileManager" ,  "appDatas" ,  "exclusiveSalesman");
                updateUserAppList(  "sampleApplication" ,  "appDatas" ,  "applicant");
                result.put("status","200");
                result.put("data","更新成功");

            } catch (Exception e) {
                result.put("status","500");
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                String msg=sw.toString();
                result.put("data",msg);
            }

             return result;
    }



        public JSONObject updateUserAppList(String bizCode, String approveFild ,String userFild) throws Exception {

        JSONObject result= new JSONObject();

        String sql="select * from i_"+bizCode;

        String updateSql="update i_"+bizCode+"  set  "+approveFild+" =";

            DataTable dataTable = SqlUtil.doQuery(sql);

            if(dataTable!=null && dataTable.getEntityRows()!=null && dataTable.getEntityRows().size()>0) {
                for (DataRow dataRow : dataTable.getEntityRows()) {
                    if(dataRow.getString(userFild)!=null) {
                        String appCode = getAppPerson(dataRow.getString(userFild));
                        User thisUser = (User)   getEngine().getOrganization().GetUnit(dataRow.getString(userFild));
                        if(thisUser!=null && thisUser.getParentID()!=null) {
                            Unit unit = getEngine().getOrganization().GetUnit(thisUser.getParentID());
                            List<String> userIds = getEngine().getOrganization().GetUsersByJobCode(unit.getObjectID(), "nqPerson", null);
                            if (userIds != null && userIds.size() > 0) {
                                for (String uid : userIds) {
                                    User userNq = (User) getEngine().getOrganization().GetUnit(uid);
                                    appCode = appCode + ";" + userNq.getCode();
                                }
                            }
                        }

                        SqlUtil.doNoQuery(updateSql + "'" + appCode + "' where  ObjectID = '" + dataRow.getString("ObjectID") + "'");
                    }
                }
            }

            result.put("status","200");
            result.put("data",bizCode+"更新成功");
            return result;
    }



}
